import deep from 'deep-get-set'
import { flattenObject, isFn, bindAll } from '../util'
import listener from '../Listener'
import { VNode } from '../vnode'

export function templateParser (template, context) {
  if (!context) return console.log('[templateParser]: context is not found')

  const views = template.views
  const flatten = flattenObject(template)
  const allFn = bindAll(getAllFn(flatten), context)

  views.forEach((item, i) => {
    views[i] = new VNode(item)
  })

  listener.push(allFn)
  Object.keys(allFn).forEach((key) => deep(template, key.replace('events.', ''), { event: key }))
  return template
}

function getAllFn (template) {
  const o = {}
  Object.keys(template).forEach((key) => {
    const val = template[key]
    if (isFn(val)) o[key] = val
  })
  return o
}
